package org.wz.complex.work.kit.clz;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

import java.util.function.BiConsumer;
import java.util.stream.Stream;

public interface FieldKit {

    public static Field getFromObject(Object obj, String property) {
        Field field = null;
        try {
            field = obj.getClass().getDeclaredField(property);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
        field.setAccessible(true);
        return field;
    }


    public static Field getOneByAnnotation(Object obj, Class<? extends Annotation> clz) {
        Field field = Stream.of(obj.getClass().getDeclaredFields())
                .filter(f -> f.getAnnotation(clz) != null)
                .findFirst()
                .get();
        field.setAccessible(true);
        return field;
    }


    public static Object getValue(Field field, Object obj) {
        try {
            field.setAccessible(true);
            return field.get(obj);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public static Long getValueForLong(Field field, Object obj) {
        return (Long) getValue(field, obj);
    }


    public static void setValue(Object entity, Field field, Object value) {
        try {
            field.setAccessible(true);
            field.set(entity, value);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static void foreachAnnotation(Class<? extends Annotation> clz, Object t, BiConsumer<Field, Annotation> consumer) {
        Stream.of(t.getClass().getDeclaredFields())
                .forEach(field -> {
                    Annotation anno = field.getDeclaredAnnotation(clz);
                    if (null != anno) {
                        consumer.accept(field, anno);
                    }
                });
    }


    static <T> Object getValueByObject(T entity, String fieldName) {
        try {
            Field field = entity.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            return field.get(entity);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    static <T> void setValueByProperty(T t, String id, Object o) {
        try {
            Field field = getFromObject(t, id);
            field.setAccessible(true);
            field.set(t, o);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }



}
